package henu.graduation_design.onlineshop;

import henu.graduation_design.adapter.OrderAdapter;
import henu.graduation_design.tool.AnalyseOrderJson;
import henu.graduation_design.util.JsonLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

public class OrderActivity extends Activity {

	SharedPreferences sp;
	ListView orderListView;
	String flagString;
	
	private JsonLoader jsonLoader = new JsonLoader();
	List<HashMap<String, Object>> list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_order);
		Intent flagIntent=getIntent();
		flagString=flagIntent.getStringExtra("flag");
		
		list=new ArrayList<HashMap<String,Object>>();
		orderListView=(ListView)findViewById(R.id.order_listview);
		
		sp = getSharedPreferences("SP", MODE_PRIVATE);
		if (!sp.getBoolean("IsLogin", false)) {
			Intent intent = new Intent(OrderActivity.this,
					LoginDialogActivity.class);
			startActivityForResult(intent, 0);
		} else {
			showOrder();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			boolean login = data.getBooleanExtra("isLogin", false);
			if (login) {
				showOrder();
			}
			break;

		default:
			Intent intent=new Intent(this,TabActivity.class);
			startActivity(intent);
			finish();
			break;
		}
	}
	
	private void showOrder() {
		sp = getSharedPreferences("SP", MODE_PRIVATE);
		try {
			if(flagString.equals("new")){
				loadJson(getString(R.string.url_get_order),
						sp,
						null);
			}else if(flagString.equals("history")){
				loadJson(getString(R.string.url_get_order_history),
						sp,
						null);
			}else {
				
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadJson(final String url, SharedPreferences spp,
			final Map<String,Object> mapEntry) {
		jsonLoader.postJson(url, spp, mapEntry,
				new JsonLoader.JsonObjectCallback() {
					public void jsonLoaded(JSONObject jsonObject) {
						list.clear();
						AnalyseOrderJson analyse = new AnalyseOrderJson(
								jsonObject,flagString);
						try {
							list=analyse.getList();
						} catch (JSONException e) {
							Toast.makeText(getApplicationContext(),
									"解析category的json数据发生异常", Toast.LENGTH_LONG)
									.show();
						}
						OrderAdapter adapter = new OrderAdapter(
								OrderActivity.this, list,sp);
						orderListView.setAdapter(adapter);
					}
				});
	}                   

}
